<template>
	<view>

		<view class="page__content" :style="{height:pageConfig.scrollHeight}">
			<u-toast ref="uToastMsg"></u-toast>
			<u-navbar>
				<view class="u-nav-slot navbar-select x-f" slot="left">

					<!-- <view class="navbar-select-t comboSelect">
						<uni-data-select placeholder="请添加设备" v-model="CheckHisValue" :localdata="HistoryDeviceList"
							iconColor="#fff" :clear="false" @change="ChangeAgreement"></uni-data-select>
					</view> -->

				</view>

				<view class="u-nav-slot" slot="right">
					<m-capsule :closeCurrent="closeAll ? 9999 : 1"></m-capsule>
				</view>
			</u-navbar>

			<view class="page__content__main">


				<view class="common__card"
					style="background-color: #fff;border-radius: 20px;margin-top: 10px;padding: 15px;font-size: 14px;min-height: 80px;">
					<view class="common__card__top">
						<view class="common__card__top__left">
							<text style="font-weight: 600;margin-left: 8px;">我的设备</text>

							<text>（{{getConnectedDevices.length}}）</text>
						</view>

						<view class="common__card__content x-f"
							style="height: 140px;background-color: #f9f9f9;border-radius: 20px;margin-top: 15px;">
							<view v-if="!getConnectedDevices.length" class="x-c" style="height: 100%;width: 100%;">
								<text style="color: #999;font-size: 12px;font-weight: 600;">当前暂无设备连接记录，请前往连接！</text>
							</view>

							<view v-else class="x-f" style="width: 100%;height: 100%;padding: 15px;overflow-x: auto;">
								<view class="device-link__card f-dc"
									style="padding: 10px;width: 200px;background-color: #fff;height: 100%;border-radius: 20px;position: relative;margin-right: 10px;"
									v-for="item in getConnectedDevices" :key="item.deviceId"
									@click="handlerClickToLink(item)">

									<view class=""
										style="position: absolute;top: 5px;right: 10px;width: 12px;height: 12px;border-radius: 12px;"
										:style="{backgroundColor: item.connected ? '#05bc4f' : '#999'}">
									</view>


									<view class="device-link__card__top" style="display: flex;align-items: center;">
										<view class="device-link__card__top__left">
											<image :src="item.config.FilePath"
												style="width: 40px;height: 40px;background-color: #f9f9f9;border-radius: 15px;">
											</image>
										</view>
										<view class="device-link__card__top__right" style="flex: 1;margin-left: 10px;">
											<view style="font-size: 14px;font-weight: 600;">
												{{item.aliasName || item.name}}
											</view>

											<view style="font-size: 12px;color: #999;" class="f-dc">
												<text>{{item.config.MeasureName}}</text>
											</view>
										</view>
									</view>

									<view class="device-link__card__content" style="flex: 1;">


									</view>

									<view class="device-link__card__bottom">
										<view style="font-size: 12px;color: #999;">
											<text>{{item.config.MeasureSpec}}</text>
										</view>
									</view>

								</view>

							</view>

						</view>
					</view>
				</view>



				<view class="deviceListBox"
					style="padding: 15px;background-color: #fff;border-radius: 20px;margin-top: 10px;">
					<!-- 标题 -->
					<view class="TitleBox" style="">
						<text class="LeftTitle">选择设备类型</text>
					</view>

					<view style="padding: 10px 0;">
						<Device :DeviceList="DeviceList"></Device>
					</view>
				</view>

			</view>


		</view>

		<!-- 导航栏右侧按钮 -- 遮罩层 -->
		<u-overlay :show="ShowRightNav" v-if="ShowRightNav" @click="ShowRightNav = false" opacity="0.4">
			<view class="warp">
				<view class="rect" @tap.stop style="overflow: hidden;">
					<u-cell title="添加设备">
						<u-icon slot="icon" size="16" name="plus"></u-icon>
					</u-cell>
					<u-cell title="扫一扫">
						<u-icon slot="icon" size="20" name="scan"></u-icon>
					</u-cell>
				</view>
			</view>
		</u-overlay>
	</view>
</template>

<script>
	import Device from "./Device/Device.vue";
	import AgreementJs from "@/static/js/Agreement.js";
	var Agreement = AgreementJs;
	import {
		mapGetters
	} from 'vuex';
	export default {
		props: {
			config: {
				type: Object,
				default: () => {
					return {
						tabbarHeight: 0,
						scrollHeight: 500
					}
				}
			},
			isPage: {
				type: Boolean,
				default: () => {
					return true
				}
			},
		},
		components: {
			Device,
		},
		data() {
			return {
				closeAll: true, // 是否返回首页
				donotSetFalseByOnUnload: false, // 卸载页面时是否设置false
				ShowRightNav: false,
				// 设备列表
				DeviceList: [],
				pageIsOpen: false,
				// 设备基础配置
				deviceConfig: {
					showPopup: false,
					formMenus: [{
						name: '取消配对',
						value: '',
						icon: 'reload',
						show: true,
					}, {
						name: '设置别名',
						value: '',
						icon: 'reload',
						show: true,
					}, ],
					setName: false,
					changeName: "",
					tempDeviceInfo: {},
					bluetoothType: false, // 蓝牙适配器是否开启
					RSSI: 0,


					findDevice: false, // 是否查询到设备
					showLoading: false,
					scanTimer: null
				}
			}
		},
		computed: {
			pageConfig() {
				console.log(this.config);
				let config = this.$utils.deepClone(this.config);
				if (this.isPage) {
					uni.createSelectorQuery().select('.content').boundingClientRect(data => {
						scrollHeight = data.height;
						console.log(scrollHeight);

						config["scrollHeight"] = scrollHeight + 'px';
						openPage();
					}).exec();
				} else {
					config["scrollHeight"] += 'px';
				}

				return config;
			},

			connectedDevices() {
				return this.$store.state.bluetooth.connectedDevices
			},
			getConnectedDevices() {
				console.log(this.$store.state.bluetooth.connectedDevices);
				const data = this.$store.state.bluetooth.connectedDevices;
				console.log(data);
				// 转为数组并按 connected 排序（connected为true的在前）
				return Object.values(data).sort((a, b) => {
					if (a.connected && !b.connected) return -1;
					if (!a.connected && b.connected) return 1;
					return 0;
				});
			},
			adapterState() { // 获取当前蓝牙适配器状态
				console.log(this.$store.state.bluetooth.adapterState);
				return this.$store.state.bluetooth.adapterState.available;
			}


		},
		watch: {
			connectedDevices: {
				handler(val) {
					console.log(val);
				},
				deep: true
			},
			getConnectedDevices: {
				handler(val) {
					console.log(val);
				},
				deep: true
			},
			// 监听蓝牙适配器状态
			adapterState: {
				async handler(nval, oval) {
					// 判断设备弹层是否打开，
					if (nval && !oval && this.deviceConfig.showPopup) {
						this.$bluetooth.isDiscovering = false;
						const initBackInfo = await this.$bluetooth.openBluetooth();
						// this.deviceConfig.bluetoothType = true;
						console.log(initBackInfo);
						if (initBackInfo.status == 0) {
							// 初始化蓝牙
							// this.initBluetoothInfo();
						} else {

							this.deviceConfig.bluetoothType = false;
						}
					}
				},
				deep: true,
			},



		},

		onLoad(option) {
			// console.log(option);
			if (!this.$utils.isEmpty(option)) {
				this.closeAll = option.hideIcon == "true";
			}


		},
		created() {
			let that = this;
			// init，打开界面及调用获取蓝牙状态
			this.GetDeviceList();

		},
		mounted() {
			var that = this;

			this.$nextTick(() => {
				setTimeout(() => {

					that.pageIsOpen = true;
				}, 500);
			});


		},
		beforeDestroy() {
			if (this.deviceConfig.scanTimer) {
				clearInterval(this.deviceConfig.scanTimer);
			}
			this.stopScan();

		},
		onUnload() {
			if (this.donotSetFalseByOnUnload) {
				// 设置智控页已全部卸载，页面栈无智控页面
				this.$store.commit('QmsModule/ChangeAndSetStateData', {
					Name1: 'DeviceLinkConfig.inControlPage',
					data: false
				});
			}
		},
		methods: {
			onMyShow() {
				let that = this;

			},
			async handlerClickToLink(data) { // 点击历史设备打开连接窗口
				let that = this;
				console.log(data);
				// this.$set(this.deviceConfig, 'tempDeviceInfo', data);
				// this.deviceConfig.tempDeviceInfo = data;
				// this.deviceConfig.showPopup = true;

				// 判断当前设备是否为蓝牙设备
				switch (data.config.Communication) {
					// 蓝牙设备
					case "Bluetooth":
					case "HID":

						uni.navigateTo({
							url: "/st_qms/Bluetooth/device_link" + "?deviceId=" + data.deviceId,
							events: {
								cancel: function(data) {
									console.log(data);
								},
								setName: function() { // 确认设置别名
									// 刷新一下
									console.log("已设置别名");
								}
							}
						})

						// const initBackInfo = await this.$bluetooth.openBluetooth();
						// if (initBackInfo.status == 0) {
						// 	// 初始化蓝牙
						// 	this.initBluetoothInfo();
						// } else {

						// 	this.deviceConfig.bluetoothType = false;
						// }

						break;
					default:
						break;
				}

			},
			async initBluetoothInfo() {
				let that = this;
				try {

					this.deviceConfig.bluetoothType = true;
					const linkType = await this.$bluetooth.isConnected(this.deviceConfig.tempDeviceInfo.deviceId);
					console.log(linkType);
					// 判断当前设备是否连接
					if (!linkType) { // 未连接
						// 开启扫描
						this.deviceConfig.findDevice = true;
						this.deviceConfig.showLoading = true;
						this.startScan();
					} else {
						this.deviceConfig.showLoading = false;
					}
				} catch (error) {
					console.log(error);
					if (error.code == "10001") {
						this.deviceConfig.bluetoothType = false;
					}
				}
			},
			// 开始扫描
			startScan() {
				let that = this;
				// 清除可能存在的旧计时器，避免重复计时
				if (this.deviceConfig.scanTimer) {
					clearInterval(this.deviceConfig.scanTimer);
					this.deviceConfig.scanTimer = null;
				}

				// 重置扫描状态
				this.deviceConfig.showLoading = true; // 显示加载中
				this.deviceConfig.findDevice = false; // 标记是否在本轮5秒内找到设备
				let currentSecond = 0; // 当前计时秒数

				// 启动蓝牙扫描
				this.$bluetooth.startDiscovery(devices => {
					// 过滤出目标设备（根据设备ID匹配）
					const targetDevice = devices.find(
						item => item.deviceId === that.deviceConfig.tempDeviceInfo.deviceId
					);

					if (targetDevice) {
						// 找到设备：更新信号强度，标记本轮已找到
						that.$set(that.deviceConfig, "RSSI", targetDevice.RSSI);
						that.deviceConfig.findDevice = true; // 关键：标记本轮找到设备
						that.deviceConfig.showLoading = false; // 隐藏加载中
					}
				});

				// 启动5秒计时器（每秒检查一次）
				this.deviceConfig.scanTimer = setInterval(() => {
					currentSecond++; // 每秒累加

					// 当计时达到5秒时
					if (currentSecond >= 5) {
						if (that.deviceConfig.findDevice) {
							// 情况1：本轮5秒内找到设备 → 重置计时，进入下一轮5秒
							uni.hideLoading();
							currentSecond = 0; // 重置秒数
							that.deviceConfig.findDevice = false; // 重置标记（等待下一轮判断）
							console.log("找到设备，进入下一轮5秒扫描");
						} else {
							uni.hideLoading();
							// 情况2：本轮5秒内未找到设备 → 停止扫描
							clearInterval(that.deviceConfig.scanTimer); // 清除计时器
							that.deviceConfig.scanTimer = null;
							that.deviceConfig.showLoading = false; // 隐藏加载中
							that.deviceConfig.findDevice = false; // 标记未找到
							that.stopScan(); // 停止蓝牙扫描
							console.log("5秒未找到设备，已停止扫描");
						}
					}
				}, 1000); // 每秒执行一次检查
			},
			// 停止扫描
			stopScan() {
				this.$bluetooth.stopDiscovery();
			},


			close_device_popup() { // 关闭设备连接弹层
				if (this.deviceConfig.setName) {
					this.deviceConfig.setName = false;
					this.deviceConfig.changeName = "";
					return;
				}

				this.deviceConfig.showPopup = false;
				// 停止扫描和计时器
				if (this.deviceConfig.scanTimer) {
					clearInterval(this.deviceConfig.scanTimer);
					this.deviceConfig.scanTimer = null;
				}
				this.stopScan();
			},






			async handlerClickByLink() { // 点击按钮搜索并连接
				let that = this;
				const deviceType = this.deviceConfig.tempDeviceInfo.connected;

				switch (deviceType) {
					case true:
						uni.showLoading({
							title: "正在断开"
						})
						// 断开设备
						this.$bluetooth.disconnectDevice(this.deviceConfig.tempDeviceInfo.deviceId, () => {
							uni.hideLoading();
							// 重新设置蓝牙状态
							this.deviceConfig.tempDeviceInfo.connected = false;
							// 开启扫描
							this.startScan();
						});

						break;
					case false:
						// 判断是否查询到设备
						if (this.deviceConfig.findDevice) {
							// 连接设备
							uni.showLoading({
								title: "正在连接"
							})
							console.log(this.deviceConfig.tempDeviceInfo);
							this.$bluetooth.connectDevice(this.deviceConfig.tempDeviceInfo, this.deviceConfig
								.tempDeviceInfo.config, () => {
									uni.hideLoading();

									that.deviceConfig.showLoading = false;
									that.deviceConfig.tempDeviceInfo.connected = true;


									if (that.deviceConfig.scanTimer) {
										clearInterval(that.deviceConfig.scanTimer);
									}
									that.stopScan();

								});

						} else {
							// 连接设备
							uni.showLoading({
								title: "正在扫描"
							})
							// 未查询到，刷新重试
							// this.$bluetooth.isDiscovering = false;
							// this.startScan();
							this.initBluetoothInfo();

						}

						break;
					default:
						break;
				}
			},
			openBluetoothAdapter() {

				let sysDeviceInfo = JSON.parse(uni.getStorageSync('sysDeviceInfo'));
				console.log(sysDeviceInfo);
				if (sysDeviceInfo['osName'] == 'ios') {} else if (sysDeviceInfo['osName'] == 'android') {
					// Native.js for Android封装一条通过JS语法直接调用Native Java接口通道，通过plus.android可调用几乎所有的系统API
					const BluetoothAdapter = plus.android.importClass(
						'android.bluetooth.BluetoothAdapter'); // 引入Java 蓝牙类
					const blueadapter = BluetoothAdapter.getDefaultAdapter(); //拿到默认蓝牙适配器方法
					console.log(blueadapter);
					if (blueadapter) {
						setTimeout(() => {
							// 判断蓝牙是否开启
							if (blueadapter.isEnabled()) {
								console.log('开启')

							} else {
								// 尝试开启蓝牙（Android原生方法）
								const isOpened = blueadapter.enable(); // 返回boolean，true表示开启成功（部分设备可能需要用户确认）
								console.log('开启结果：', isOpened);
							}
						}, 50)
					}
				}
			},

			deviceConfig_popup_menu(data) { // 点击弹层气泡
				switch (data.name) {
					case "取消配对":
						// 1、断开连接
						this.$bluetooth.disconnectDevice(this.deviceConfig.tempDeviceInfo.deviceId);

						const deviceInfo = this.$utils.deepClone(this.$store.state.bluetooth.connectedDevices);
						// 2、删除设备信息
						Object.keys(deviceInfo).forEach(item => {
							delete deviceInfo[this.deviceConfig.tempDeviceInfo.deviceId]
						});


						this.$store.commit("bluetooth/ChangeAndSetStateData", {
							Name1: 'connectedDevices',
							data: deviceInfo,
							StorageName: "connectedDevices",
							StorageData: JSON.stringify(deviceInfo)
						});

						// 关闭弹层
						this.close_device_popup();

						break;

					case "设置别名":

						this.deviceConfig.setName = true;
						this.deviceConfig.changeName = this.deviceConfig.tempDeviceInfo.aliasName ? this.deviceConfig
							.tempDeviceInfo.aliasName : this.deviceConfig.tempDeviceInfo.name;


						break;
					default:
						break;
				}
			},

			// 
			handlerSetDeviceName(str) {
				let that = this;
				console.log(that.deviceConfig.tempDeviceInfo.deviceId);
				console.log(this.deviceConfig.changeName);

				let title = str == 1 ? "是否确认设置" : "是否确认重置"

				this.$utils.layer.confirm(title, (ret) => {
					console.log(action);
					const {
						action
					} = ret;

					if (action == "confirm") {
						let lastName = ""
						if (str == 1) {
							lastName = that.deviceConfig.changeName
						} else {
							lastName = that.deviceConfig.tempDeviceInfo.name
						}

						that.$bluetooth.setDeviceAlias(that.deviceConfig.tempDeviceInfo.deviceId, lastName);

					}
					that.deviceConfig.setName = false;
					that.deviceConfig.changeName = "";
				})


			},





			ChangeAgreement(index) { // 切换下拉框时
				let that = this

			},



			GetDeviceList() { // 获取分类
				var that = this

				that.Request.request('APP_JLSBFLLIST1', {}, function(res) {
					console.log(res);
					if (res.status == 200) {

						function tranList(list, rootVal, PID, ID) {
							var childItem = [];
							for (var i = 0; i < list.length; i++) {
								var childObj = {}
								if (list[i][PID] == rootVal) {
									childObj = list[i];
									childObj.children = tranList(list, list[i][ID], PID, ID);
									childItem.push(childObj);
								}
							}
							return childItem;
						}

						let TreeData = tranList(res.data.ds, 0, 'UpID', 'MeasureTypeID')

						TreeData[0].children.forEach(item => {
							let ChildrenList = []
							res.data.ds1.forEach(ReItem => {
								if (ReItem.UpID == item.MeasureTypeID) {
									ChildrenList.push(ReItem)
								}
							})
							item.children = ChildrenList
						})
						console.log(TreeData[0]);
						// console.log(JSON.stringify(TreeData))
						that.DeviceList = TreeData[0].children
					}
				})

			},





		}
	}
</script>

<style lang="scss">
	* {
		padding: 0;
		margin: 0;
		box-sizing: border-box;
	}

	.page__content {
		padding: 0 15px;
		/* 给顶部盒子安全高度 */
		padding-top: var(--status-bar-height);
		// background-color: #fff;
		background-color: #f7f7f7;


		// 顶部导航栏 navbar点击左侧会有改变透明的的操作，直接强制赋值为1
		.u-navbar__content__left {
			opacity: 1 !important;
		}

		.comboSelect {

			::v-deep .uni-stat-box {
				background-color: transparent !important;
			}

		}

		::v-deep .uni-select {
			min-width: 150px;
			border: none !important;

			.uni-select__input-box {

				.uni-select__input-text,
				.uni-select__input-placeholder {
					color: #fff !important;
				}

				// 下拉框内文字样式
				.uni-select__input-text {
					color: #fff !important;
				}

				.uni-icons {
					color: #fff !important;
				}
			}
		}
	}

	.u-nav-slot {
		/* min-width: 80px; */
		width: fit-content;



	}


	// 顶部右侧导航按钮样式
	.warp {
		display: flex;
		align-items: flex-start;
		justify-content: flex-end;
		height: 100%;

		.rect {
			margin: 30px 12px 0 0;
			min-width: 140px;
			min-height: 30px;
			background-color: #fff;
			border-radius: 12px;
		}
	}

	.page__content__main {
		// padding: 0 15px;
		margin-top: 50px;
		height: 100vh;
		overflow: auto;

		.TitleText {
			font-size: 24px;
			color: #333;
		}

		// 将吸顶栏的层级往下降，防止下拉框被盖住
		.u-sticky {
			z-index: 1 !important;

			// 吸顶
			.StickyBox {
				background-color: #fff;
				padding: 15px;
				border-radius: 20px;
				border-bottom: 4px solid #f7f7f7;

				.StickyText {
					display: flex;
					align-items: center;
					// background-color: #f6f6f6;
					height: 20px;
					line-height: 20px;

					.Round {
						width: 10px;
						height: 10px;
						border-radius: 50%;
						background-color: #49e606;
					}

					.RoundRed {
						width: 10px;
						height: 10px;
						border-radius: 50%;
						background-color: #ff0000;
					}


					.Text {
						font-size: 12px;
						margin-left: 6px;
						display: flex;
						align-items: center;

						.TextBox {
							width: fit-content;
							margin-left: 4px;
						}

						.NotText {
							width: fit-content;
							margin-left: 4px;
						}
					}
				}

				.refreshBox {
					position: absolute;
					right: 15px;
					top: 50%;
					font-size: 14px;
					color: #00aa00;
					transform: translateY(-50%);
				}
			}
		}

		// 操作界面
		.BlueToothBox {
			border: 1px solid #f7f7f7;
			border-radius: 20px;
			margin-top: 5px;
			margin-bottom: 5px;
			// height: 30vh;
			height: 300rpx;
			overflow: auto;



			.FormDataBox {

				// 插口
				.uni-forms-item {

					.uni-forms-item__label {
						align-items: flex-end !important;
						background-color: pink !important;
					}

					.uni-select {
						border: none !important;

						&::after {
							position: absolute;
							box-sizing: border-box;
							content: ' ';
							pointer-events: none;
							right: 16px;
							bottom: 0;
							left: 16px;
							border-bottom: 1px solid #cbcdcf;
							-webkit-transform: scaleY(0.5);
							transform: scaleY(0.5);
						}

						// &:last-child::after {
						// 	border-bottom: none !important;
						// }
					}

				}
			}
		}

		// 标题
		.TitleBox {
			margin-top: 10px;

			.LeftTitle {
				font-size: 14px;
				font-weight: 600;
				margin-left: 8px;
			}
		}
	}

	.row {
		display: flex;
		flex-direction: row;
		align-content: flex-start;
		align-items: flex-start;
		margin: 15px 10px;
		padding: 5px;

		.button {
			width: 100px;
			font-size: 11px;
			background-color: #003366;
			color: white;
		}
	}

	.border {
		border: solid 1px gray;
	}

	.list {
		padding-left: 3vw;
		padding-right: 3vw;
		padding-top: 3vw;

		.list-item {
			background-color: #f8f8f8;
			border: solid 1px darkgray;
			box-shadow: 1px 1px 3px;
			margin-bottom: 3vw;

			.text {
				height: 30px;
				line-height: 30px;
				margin-left: 5px;
			}

			.row {
				margin: 3px 10px !important;
				padding: 0 !important;
			}
		}
	}

	.log {
		width: 87vw;
		font-size: 13px;
		color: #003366;

		.log-bottom {
			height: 10vw;
		}
	}
</style>